﻿#Include ..\builtin\exec.ahk
#Include ..\baseHandle.ahk

class Exec2 extends BaseHandle {

  static Handle(parsed) {
    target := LTrim(parsed.raw.substring(parsed.which.Length + 1))
    cs := target.toCharArray()
    ec := '\', qc := "'", i := 1, _q := false, s := '', r := [], cmds := [], ops := []
    while i <= cs.Length {
      esc := false
      if cs[i] = ec
        esc := !esc, i++
      if !esc and cs[i] = qc {
        _q := !_q, i++
        continue
      }
      if !_q and !esc {
        switch cs[i] {
          case '|': cmds.Push(s.Trim()), ops.Push(0), s := ''
          case '&': cmds.Push(s.Trim()), ops.Push(1), s := ''
          case '^': cmds.Push(s.Trim()), ops.Push(2), s := ''
          case ';': cmds.Push(s.Trim()), ops.Push(3), s := ''
          default: s .= cs[i]
        }
      } else s .= cs[i]
      i++
    }
    if !(s := Trim(s))
      return this.Fail('empty element(' i - 1 ')')
    cmds.Push(s)

    last := Exec.Handle({ target: cmds[1] }), _i := 2
    last.r := escapeChs(last.r, '\', "'")
    r.Push(Format('{}({})-{}', last.flag ? 'Y' : 'N', r.Length + 1, last.r))

    for i, v in ops {
      switch v {
        case 0:
          last := Exec.Handle({ target: cmds[_i++] ' ' last.r })
        case 1:
          if !last.flag {
            r.Push('Interrupted')
            return this.Succ(r.Join('`n'))
          }
          last := Exec.Handle({ target: cmds[_i++] })
        case 2:
          if last.flag {
            r.Push('Interrupted')
            return this.Succ(r.Join('`n'))
          }
          last := Exec.Handle({ target: cmds[_i++] })
        case 3:
          last := Exec.Handle({ target: cmds[_i++] })
      }
      last.r := escapeChs(last.r, '\', "'")
      r.Push(Format('{}({})-{}', last.flag ? 'Y' : 'N', r.Length + 1, last.r))
    }

    return  this.Succ(r.join('`n'))
  }

  static Echo() => '
  (
    e 增强内置Exec命令
    e <target>... (|;^&)
  )'

}
